package com.mms.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

public class App {
	final static int PORT = 8080;

	public static void main(String[] args) throws Exception {
		kill(); // 如果你在Mac系统上运行，请注释该行
		createWebAppDir();
		debug();
	}

	/**
	 * 杀掉正在运行的tomcat实例，释放端口，仅适用于Windows系统。
	 * 
	 * @throws IOException
	 */
	private static void kill() throws IOException {
		Process process = Runtime.getRuntime().exec("netstat -aon");
		BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			if (line.contains(":" + PORT + " ") && line.contains("LISTENING")) {
				String[] split = line.split("\\s+");
				String pid = split[split.length - 1];
				Runtime.getRuntime().exec("TASKKILL /F /PID " + pid);
				break;
			}
		}
	}

	private static void createWebAppDir() {
		File file = new File("src/main/webapp");
		if (file.exists()) {
			return;
		}
		file.mkdir();
	}

	/**
	 * 启动新的tomcat实例
	 * 
	 * @throws LifecycleException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	private static void debug() throws LifecycleException, InstantiationException, IllegalAccessException {

		String webappDirLocation = "src/main/webapp";
		Tomcat tomcat = new Tomcat();

		// The port that we should run on can be set into an environment variable
		// Look for that variable and default to 8080 if it isn't there.
		tomcat.setHostname("localhost");
		tomcat.setPort(PORT);

		Context ctx = tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
//		ctx.addServletContainerInitializer(new ServletContainerInitializer() {
//			public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
//				ctx.addFilter("encodingFilter", new EncodingFilter()).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
//				ctx.addFilter("corsFilter", new CORSFilter()).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
//			}
//		}, null);

		ctx.setReloadable(true);

		tomcat.getConnector();

		// Declare an alternative location for your "WEB-INF/classes" dir
		// Servlet 3.0 annotation will work
		File additionWebInfClasses = new File("target/classes");
		WebResourceRoot resources = new StandardRoot(ctx);
		resources.addPreResources(
				new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
		ctx.setResources(resources);

		tomcat.start();
		tomcat.getServer().await();
	}
}
